#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>//TODO: 某些头文件
#define MAX_BUFFER 1024

int main(int argc, char* argv[]) {
    int  local_socket;
    int  return_code;
    char send_and_receive_buffer[MAX_BUFFER];
    int  port_number;
    int  nr_bytes_read;

    static struct sockaddr_in server_sockaddr;

    //客户端运行需要给出具体的连接地址和端口 
    if (argc != 3) {
        printf("Usage: %s server_ip_address port_number \n", argv[0]);
        return 1;
    }

    //获得输入的端口
    port_number = atoi(argv[2]);

    //创建套节字用于客户端的连接
    local_socket = socket(PF_INET, SOCK_STREAM, 0);//TODO: 调用socket
    if (local_socket < 0) {//TODO: 如果错误
        perror("ERR socket.");
        return 1;
    }

    //填充关于服务器的套节字信息
    memset(&server_sockaddr, 0, sizeof(server_sockaddr));
    server_sockaddr.sin_family = AF_INET;
    server_sockaddr.sin_addr.s_addr = inet_addr(argv[1]);
    server_sockaddr.sin_port = htons(port_number);

    //连接指定的服务器 
    return_code = (local_socket,(struct sockaddr *)&server_sockaddr, sizeof(server_sockaddr));//TODO: 调用connect
    if (return_code == -1) {//TODO: 如果错误
        perror("ERR connect.");
        close(local_socket);
        return 1;
    }

    memset(send_and_receive_buffer, 0, MAX_BUFFER);
    //用户输入信息后，程序将输入的信息通过套接字发送给服务器 ，然后调用read函数从服务器中读取发送来的信息。
    //输入“#”退出 
    while (1) {
        //TODO: 12345 改为自己的学号，此处不要修改write调用和STDOUT_FILENO参数！
        write(STDOUT_FILENO, "Type in a string for 201930310050:", strlen("Type in a string for 201930310050:"));
        nr_bytes_read = read(STDOUT_FILENO, send_and_receive_buffer, MAX_BUFFER);//TODO: 调用read, 从STDIN_FILENO读
        if (nr_bytes_read > 0)
            write(local_socket, send_and_receive_buffer, nr_bytes_read);//TODO: 调用write，写socket
        nr_bytes_read = read(local_socket, send_and_receive_buffer, nr_bytes_read);//TODO: 调用read，读socket
        if (nr_bytes_read > 0)
            printf("Message form server: %s\n", send_and_receive_buffer);
        if (send_and_receive_buffer[0] == '#')
            break;
        //提示：刚才几句忽略了某些可能的错误，你能加上么？
    }
    close(local_socket);
    return 0;
}
